package com.duke.shaking.widget;

import java.lang.reflect.Method;

import com.duke.shaking.Constants;
import com.duke.shaking.R;
import com.duke.shaking.BaseActivity;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TableRow;
import android.widget.TextView;

public class FormRow extends TableRow implements OnClickListener {

	protected static final int RowHeightDef = 42; // in dip
	protected static final int PaddingLeft = 7; // in dip
	protected static final int PaddingRight = 7; // in dip
	
	protected int       mLayoutId;
	protected ViewGroup mMainLayout;
	protected LayoutInflater mLayoutFactory;
	protected int       mIconId;
	protected ImageView mImgIcon;
	protected TextView  mLabel;
	protected String    mLabelValue;
	protected TextView  mText;
	protected String    mTextValue;
	protected ImageView mImgPopup;
	protected String    mHint;
	protected String    mPopupEditorClass;
	protected String    mStartActivityClassName;
	protected Class<?>  mStartActivityClass;
	protected String    mOnClickMethodName;
	protected Method    mOnClickMethod;
	protected boolean   mHasBottomLine;
	protected int       mBottomLineColor;
	protected int       mBottomLineWidth; // in pixel
	protected int       mRowHeight; // in pixel
	
	protected Paint paint;
	protected Rect  bottomLineRect;
	    
	public FormRow(Context context, AttributeSet attrs) {
		super(context, attrs);
		// TODO Auto-generated constructor stub
		init(attrs);
	}

	private void init(AttributeSet attrs) {
		mLayoutId = R.layout.view_editor_row;
		mIconId = -1;
		mHasBottomLine = false;
		mBottomLineColor = Color.argb(0xff,0xa8, 0xab, 0xad);
		mBottomLineWidth = 1;
		mRowHeight = BaseActivity.dip2px(RowHeightDef);
		initAttrs(attrs);
		initViews();
	}
	
	protected void initAttrs(AttributeSet attrs) {
		TypedArray a = getContext().obtainStyledAttributes(attrs,
                R.styleable.shaking);
		
		if (a == null) {
			return;
		}
		
		for (int i = 0; i < a.getIndexCount(); i ++) {
            int attr = a.getIndex(i);
            switch (attr) {
            case R.styleable.shaking_layout:
            	mLayoutId = a.getResourceId(attr, mLayoutId);
            	break;
            case R.styleable.shaking_icon:
            	mIconId = a.getResourceId(attr, mIconId);
            	break;
            case R.styleable.shaking_hint:
            	mHint = a.getString(attr);
            	break;
            case R.styleable.shaking_label:
            	mLabelValue = a.getString(attr);
            	break;
            case R.styleable.shaking_text:
            	mTextValue = a.getString(attr);
            	break;
            case R.styleable.shaking_startActivity:
            	mStartActivityClassName = a.getString(attr);
            	break;
            case R.styleable.shaking_popupEditor:
            	mPopupEditorClass = a.getString(attr);
            	break;
            case R.styleable.shaking_onClick:
            	mOnClickMethodName = a.getString(attr);
            	break;
            case R.styleable.shaking_hasBottomLine:
            	mHasBottomLine = a.getBoolean(attr, mHasBottomLine);
            	break;
            case R.styleable.shaking_bottomLineColor:
            	mBottomLineColor = a.getColor(attr, mBottomLineColor);
            	break;
            case R.styleable.shaking_bottomLineWidth:
            	mBottomLineWidth = a.getDimensionPixelSize(attr, mBottomLineWidth);
            	break;
            case R.styleable.shaking_rowHeight:
            	mRowHeight = a.getDimensionPixelSize(attr, mRowHeight);
            	break;
            }
        }
        a.recycle();
	}
	
	protected LayoutInflater getLayoutFactory() {
		if (mLayoutFactory == null) {
			mLayoutFactory = LayoutInflater.from(getContext());
		}
		return mLayoutFactory;
		
	}
	
	protected View createViewById(int viewId) {
		if (viewId <= 0) {
			return null;
		}
		LayoutInflater factory = getLayoutFactory();
		return factory.inflate(viewId, null);
	}
	
	private String getFullClassName(String className) {
		if (className.startsWith(".")) {
			return Constants.packageName + className;
		}
		return className;
	}
	
	public void setOnClickMethod(String methodName) {
		try {
			mOnClickMethodName = methodName;
			Class<?>[] parameterTypes = new Class[1];
			parameterTypes[0] = View.class;
			mOnClickMethod = getContext().getClass().getMethod(mOnClickMethodName, parameterTypes);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			//e.printStackTrace();
			mOnClickMethod = null;
		}
		if (mMainLayout != null && mImgPopup != null) {
			if (mStartActivityClass == null && mOnClickMethod == null) {
				mImgPopup.setVisibility(View.INVISIBLE);
				setOnClickListener(null);
			}
			else {
				mImgPopup.setVisibility(View.VISIBLE);
				setOnClickListener(this);
			}
		}
	}
	
	public void setOnClickStartAcvitity(Class<?> startActivityClass ) {
		
		mStartActivityClass = startActivityClass;	
		
		if (mMainLayout != null && mImgPopup != null) {
			if (mStartActivityClass == null && mOnClickMethod == null) {
				mImgPopup.setVisibility(View.INVISIBLE);
				setOnClickListener(null);
			}
			else {
				mImgPopup.setVisibility(View.VISIBLE);
				setOnClickListener(this);
			}
		}
	}
	
	protected void initViews() {
		this.setPadding(BaseActivity.dip2px(PaddingLeft), 
				0, 
				BaseActivity.dip2px(PaddingRight), 
				0);
		mMainLayout = (ViewGroup)createViewById(mLayoutId);
		if (mMainLayout != null) {
			LayoutParams lp = (LayoutParams)generateDefaultLayoutParams();
			lp.weight = 1.0f;
			lp.height = mRowHeight;
			addView(mMainLayout, lp);
			mImgIcon = (ImageView)mMainLayout.findViewById(R.id.img_edtor_row_icon);
			if (mImgIcon != null) {
				if (mIconId <= 0) {
					mImgIcon.setVisibility(GONE);
				}
				else {
					mImgIcon.setImageResource(mIconId);
					mImgIcon.setVisibility(VISIBLE);
				}
			}
			mText = (TextView)mMainLayout.findViewById(R.id.txt_edtor_row_text);
			if (mText != null) {
				if (mHint != null) {
					mText.setHint(mHint);
				}
				if (mTextValue != null) {
					mText.setText(mTextValue);
				}
			}
			
			mLabel = (TextView)mMainLayout.findViewById(R.id.txt_edtor_row_label);
			if (mLabel != null) {
				if (mLabelValue != null) {
					mLabel.setText(mLabelValue);
				}
			}
		}
		
		setBackgroundColor(Color.TRANSPARENT);
		
		try {
			if (mStartActivityClassName != null) {
				mStartActivityClass = Class.forName(getFullClassName(mStartActivityClassName));
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			//e.printStackTrace();
			mStartActivityClass = null;
		}
		
		/*
		try {
			if (mPopupEditorClass != null) {

				Class<?> c = Class.forName(getFullClassName(mPopupEditorClass));
				Constructor<?> con = c.getConstructor(Context.class);
				mPopupEditor = (PopupEditor)con.newInstance(getContext());
				mPopupEditor.setParentRow(this);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			//e.printStackTrace();
			mPopupEditor = null;
			TLog.e("can not instance the PopupEditor - " + mPopupEditorClass 
				+ ", " + e.getMessage());
		}
		*/
		
		try {
			Class<?>[] parameterTypes = new Class[1];
			parameterTypes[0] = View.class;
			mOnClickMethod = getContext().getClass().getMethod(mOnClickMethodName, parameterTypes);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			//e.printStackTrace();
			mOnClickMethod = null;
		}
		if (mMainLayout != null) {
			mImgPopup = (ImageView)mMainLayout.findViewById(R.id.img_popup);
			if (mStartActivityClass == null && mOnClickMethod == null) {
				mImgPopup.setVisibility(View.INVISIBLE);
			}
			else {
				mImgPopup.setVisibility(View.VISIBLE);
				setOnClickListener(this);
			}
		}
	}
	
	@Override
	protected void onDraw(Canvas canvas) {
		if (!mHasBottomLine) {
			super.onDraw(canvas);
			return;
		}
		
		if (paint == null) {
			paint = new Paint();
			paint.setColor(mBottomLineColor);
			paint.setStrokeWidth(mBottomLineWidth);
			paint.setStyle(Style.FILL);
		}
		
		canvas.drawLine(0, getHeight() - mBottomLineWidth, 
				getWidth(), getHeight() - mBottomLineWidth, paint); 
		super.onDraw(canvas);
	}
	
	public void setText(String text) {
		if (mText != null) {
			mText.setText(text);
		}
	}

	public void onClick(View v) {
		// TODO Auto-generated method stub
		if (v == this) {
			if (mOnClickMethod != null) {
				Object[] args = new Object[1];
				args[0] = v;
				try {
					mOnClickMethod.invoke(getContext(), args);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					Log.e("shaking", "except when invoke method: " 
							+ mOnClickMethodName + e.getMessage());
				}
			}
			else if (mStartActivityClass != null) {
				((BaseActivity)getContext()).go(mStartActivityClass);
			}
		}
	}

}
